package com.dha.asynctask;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dha.adapter.XemThoiKhoaBieuAdapter;
import com.dha.caodangcongnghe.R;
import com.dha.model.ThoiKhoaBieuModel;
import com.dha.variable.DangNhapVariable;
import com.dha.variable.ThongTinTaiKhoan;
import com.dha.variable.XemThoiKhoaBieuVariable;

public class XemThoiKhoaBieuAsyncTask extends AsyncTask<Void, String, Integer> {
	private TextView tvHoTen;
	private TextView tvMaso;
	private ProgressDialog dialog;

	private Activity activity;

	private ListView listView;

	private ArrayList<ThoiKhoaBieuModel> arr;

	private XemThoiKhoaBieuAdapter adapter;

	private String maSo = null;
	//
	private final int KHONG_CO_TEN = 100;
	private final int KHONG_CO_THOI_KHOA_BIEU_HOC_KY_HIEN_TAI = 101;
	private final int CO_LOI_LAY_TEN = 102;
	private final int OK = 103;
	private final int CO_LOI_LAY_TKB = 104;

	// cái này để chuyển từ dạng "yyyy-MM-dd'T'HH:mm:ss" bên sql qua
	private SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss");
	// // cái này để chuyển sang dạng mong muốn
	private SimpleDateFormat dateOutput = new SimpleDateFormat("dd/MM/yyyy");

	public XemThoiKhoaBieuAsyncTask(Activity activity, String maSo) {
		super();
		this.activity = activity;
		listView = (ListView) activity.findViewById(R.id.lv_DS_TKB);
		arr = new ArrayList<ThoiKhoaBieuModel>();

		adapter = new XemThoiKhoaBieuAdapter(activity,
				R.layout.layout_xemtkb_custom_table, arr);

		listView.setAdapter(adapter);
		this.maSo = maSo;

		tvHoTen = (TextView) this.activity.findViewById(R.id.tv_hoTen_TKB);
		tvMaso = (TextView) this.activity.findViewById(R.id.tv_maSV_TKB);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		tvHoTen.setText(null);
		tvMaso.setText(null);
		dialog = ProgressDialog.show(activity, "Vui lòng chờ",
				"Đang tải thời khóa biểu về");
		super.onPreExecute();
	}

	@Override
	protected Integer doInBackground(Void... params) {
		try {
			SoapObject requestThongTin = new SoapObject(
					DangNhapVariable.NAME_SPACE_DANGNHAP,
					DangNhapVariable.METHOD_NAME_THONGTIN);

			PropertyInfo maSoinfoThongTin = new PropertyInfo();
			maSoinfoThongTin.setName("MaSo");
			maSoinfoThongTin.setValue(maSo);
			requestThongTin.addProperty(maSoinfoThongTin);
			SoapSerializationEnvelope envelopeThongTin = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelopeThongTin.setOutputSoapObject(requestThongTin);

			HttpTransportSE httpTransportSEThongTin = new HttpTransportSE(
					DangNhapVariable.URL_DANGNHAP);
			httpTransportSEThongTin.call(DangNhapVariable.SOAP_ACTION_THONGTIN,
					envelopeThongTin);

			SoapPrimitive responeThongTin = (SoapPrimitive) envelopeThongTin
					.getResponse();
			if (responeThongTin != null) {
				// Lưu thông tin vào các biến static
				ThongTinTaiKhoan.hoTenThoiKhoaBieu = responeThongTin.toString();
				ThongTinTaiKhoan.maSoThoiKhoaBieu = maSo;
			} else {
				return KHONG_CO_TEN;
			}

		} catch (Exception ex) {
			return CO_LOI_LAY_TEN;
		}

		SoapSerializationEnvelope envelope = null;
		try {
			SoapObject request = new SoapObject(
					XemThoiKhoaBieuVariable.NAME_SPACE,
					XemThoiKhoaBieuVariable.METHOD_NAME_XEMTHOIKHOABIEUHOCKYHIENTAI);
			PropertyInfo maSoInfo = new PropertyInfo();
			maSoInfo.setName("MaSo");
			maSoInfo.setValue(maSo);
			request.addProperty(maSoInfo);

			envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);

			HttpTransportSE httpTransportSE = new HttpTransportSE(
					XemThoiKhoaBieuVariable.URL);
			httpTransportSE
					.call(XemThoiKhoaBieuVariable.SOAP_ACTION_XEMTHOIKHOABIEUHOCKYHIENTAI,
							envelope);

			Vector<SoapObject> respone = (Vector<SoapObject>) envelope
					.getResponse();
			if (respone != null) {
				for (SoapObject so : respone) {
					publishProgress(so.getProperty("maLopHocPhan").toString(),
							so.getProperty("tenHocPhan").toString(), so
									.getProperty("thu").toString(), so
									.getProperty("tuTiet").toString(), so
									.getProperty("denTiet").toString(), so
									.getProperty("tenGiaoVien").toString(), so
									.getProperty("phong").toString(), so
									.getProperty("ngayHieuLuc").toString());
				}
				return OK;
			} else {
				return KHONG_CO_THOI_KHOA_BIEU_HOC_KY_HIEN_TAI;
			}

		} catch (java.lang.ClassCastException ex) {
			SoapObject so;
			try {
				so = (SoapObject) envelope.getResponse();
				if (so != null) {
					publishProgress(so.getProperty("maLopHocPhan").toString(),
							so.getProperty("tenHocPhan").toString(), so
									.getProperty("thu").toString(), so
									.getProperty("tuTiet").toString(), so
									.getProperty("denTiet").toString(), so
									.getProperty("tenGiaoVien").toString(), so
									.getProperty("phong").toString(), so
									.getProperty("ngayHieuLuc").toString());
					return OK;
				} else {
					return KHONG_CO_THOI_KHOA_BIEU_HOC_KY_HIEN_TAI;
				}
			} catch (SoapFault e) {
				// TODO Auto-generated catch block
				return CO_LOI_LAY_TKB;
			}

		} catch (Exception e) {
			return CO_LOI_LAY_TKB;
		}
	}

	@Override
	protected void onProgressUpdate(String... values) {
		String lop = values[0].toString();
		String monHoc = values[1].toString();
		String thu = values[2].toString();
		String tuTiet = values[3].toString();
		String denTiet = values[4].toString();
		String tenGiaoVien = values[5].toString();
		String phong = values[6].toString();
		String ngayDangTuSQL = values[7].toString();
		String ngayDangInRa = null;
		try {
			// Chuyển dạng tring lấy ra quên sql, service qua dạng ngày
			Date date = dateFormat.parse(ngayDangTuSQL.substring(0, 19));
			// chuyển ngược về lại dạng mong muốn
			ngayDangInRa = dateOutput.format(date);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			Log.i("hehe", e1.toString());
		}

		ThoiKhoaBieuModel tkb = new ThoiKhoaBieuModel(lop, monHoc, thu, tuTiet,
				denTiet, tenGiaoVien, phong, ngayDangInRa);
		arr.add(tkb);

		super.onProgressUpdate(values);
	}

	@Override
	protected void onPostExecute(Integer result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		AlertDialog.Builder builder = null;
		builder = new Builder(activity);
		builder.setNegativeButton("Đóng", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				activity.finish();
			}
		}).setTitle("Lỗi");
		AlertDialog alertDialog = null;
		switch (result) {
		case KHONG_CO_TEN:
			builder.setMessage("Tài khoản " + maSo + " không tồn tại");

			alertDialog = builder.create();
			alertDialog.show();
			break;
		case CO_LOI_LAY_TEN:

			builder.setMessage("Tài khoản " + maSo + " không tồn tại");

			alertDialog = builder.create();
			alertDialog.show();
			break;
		case KHONG_CO_THOI_KHOA_BIEU_HOC_KY_HIEN_TAI:
			builder.setMessage(ThongTinTaiKhoan.hoTenThoiKhoaBieu
					+ " Không có thời khóa biểu học kỳ hiện tại");

			alertDialog = builder.create();
			alertDialog.show();
			break;
		case OK:
			tvHoTen.setText(ThongTinTaiKhoan.hoTenThoiKhoaBieu);
			tvMaso.setText(maSo);
			adapter.notifyDataSetChanged();

			break;
		case CO_LOI_LAY_TKB:
			builder.setMessage("Lỗi trong việc lấy thời khóa biểu của "
					+ ThongTinTaiKhoan.hoTenThoiKhoaBieu);

			alertDialog = builder.create();
			alertDialog.show();
			break;
		}
		dialog.dismiss();
	}

}
